<!DOCTYPE html>
<html lang="en">

<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<meta http-equiv="X-UA-Compatible" content="ie=edge">
	<title>Document</title>
	<link rel="stylesheet" href="./bootstrap/css/bootstrap.css">
	<link rel="stylesheet" href="./css/base.css">
	<style>
		.crumbs {
			font-size: 14px;
			color: #ccc;
		}

		.content .item {
			margin-top: 10px;
			margin-bottom: 10px;
		}

		.content .item img {
			width: 100%;
			height: 100%;
			box-shadow: 0px 0px 10px #ccc;

		}

		.content .item .title:hover {
			text-decoration: underline;
			cursor: pointer;
		}


		.content .item div:first-child:hover img {
			opacity: 0.7;
			cursor: pointer;
			transition: all 0.3s ease-in-out;
		}

		.content .item .intro {
			margin-top: 10px;
			color: #ccc;
			font-size: 14px;
		}
	</style>
</head>

<body>
	<div class="container">
		<nav class="navbar navbar-default">
			<div class="container-fluid">
				<!-- Brand and toggle get grouped for better mobile display -->
				<div class="navbar-header">
					<button type="button" class="navbar-toggle collapsed" data-toggle="collapse"
						data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
						<span class="sr-only">Toggle navigation</span>
						<span class="icon-bar"></span>
						<span class="icon-bar"></span>
						<span class="icon-bar"></span>
					</button>
					<a class="navbar-brand" href="#" style="display:flex;">
						小罗的博客
					</a>
				</div>

				<!-- Collect the nav links, forms, and other content for toggling -->
				<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">

					<ul class="nav navbar-nav navbar-right">
						<li><a href="#">首页</a></li>
						<li class="dropdown">
							<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button"
								aria-haspopup="true" aria-expanded="false">分类 <span class="caret"></span></a>
							<ul class="dropdown-menu" id="cates">
							
							</ul>
						</li>
						<li><a href="/tags.html">标签</a></li>
						<li><a href="/about.html">关于我</a></li>
					</ul>
				</div><!-- /.navbar-collapse -->
			</div><!-- /.container-fluid -->
		</nav>

		<div>
			<h4 class="crumbs" style="text-align:left;">当前位置：首页 / 所有分类 / 体育 </h4>
		</div>

		<div class="content">
			<div class="artlist" id="cateArticles">
				

			</div>
		</div>

		<button type="button" id="loadMore" class="btn  btn-block">查看更多</button>
		<hr>

		<div class="footer" style="text-align:center;font-size: 14px; color: #999;margin:10px 0;">
			首页 | 主站 | GitHub | created at 2020/02/4 | Powered by 小罗
		</div>
	</div>
</body>
<script src="./js/jquery.js"></script>
<script src="./bootstrap/js/bootstrap.min.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/layer/3.5.1/layer.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/nprogress/0.2.0/nprogress.js"></script>
<script src="https://momentjs.bootcss.com/downloads/moment.min.js"></script>
<script>
	let page =1;
	let pagesize = 2;
	let isFinish = false;
	let imgs;
	let url = location.href;
	// console.log(url);
	let reg = /\?cat_id=(.+)\&?/;
	// console.log(reg);
	let [,cat_id] = Array.from(url.match(reg));
	console.log(cat_id);
	
	if(isNaN(parseInt(cat_id))){
		layer.msg('请求错误')
		location.href='/'
	}
	$('#loadMore').click(function(res){
		if(isFinish){
			layer.msg('数据加载完毕',{icon:4})
			$(this).prop('disabled',true).html('加载完毕了');

			return;
		}
	    // isFinish('disabled')
		page++;
		loadCateArticle(page,pagesize,cat_id).then(res=>{
			if(res.length < pagesize){
				isFinish = true;
			}
			$(this).prop('disable',false).html('加载更多')
			let articlesHtml = renderCateArticle(res);
			let oldcateHtml = $('#cateArticles').html()
			$('#cateArticles').html(oldcateHtml + articlesHtml)
			imgs = document.querySelectorAll('img');
			scrollHandle(imgs);
		})
	})
	
	//加载分类文章
	function loadCateArticle(page,pagesize,cat_id){
		NProgress.set(0.4)
		return $.ajax({
			url:`http://127.0.0.1:8080/api/cateArticle?cat_id=${cat_id}`,
			data:{page,pagesize},
			complete(){
				NProgress.done()
			}
		})
	}
	//渲染分类数据
	function renderCate(cates){
		console.log(cates);
		let lis ='';
		cates.forEach(cate =>{
			let {cat_id,cate_name}=cate;
			// console.log(cate);
			lis += `<li><a href="/cate.html?cat_id=${cat_id}">${cate_name}</a></li>`
		});
		return lis;
	}
	//加载分类
	function loadCate(){
		return $.ajax({
			url:"http://127.0.0.1:8080/api/cate"
		})
	}
	//加载分类的文章
	function renderCateArticle(articles){
		let divs ='';
		console.log(articles);
		articles.forEach(article=>{
			let {id,img,author,add_time,cat_id,cate_name,title,content} =article;
			if(!img){
				img = "http://placehold.it/200x140/ffde00/aaabbb?text=xiaoluo"
			}else{
				img = 'http://127.0.0.1:8080/'+img;
			}
			add_time = (moment(add_time).format('YYYY-MM-DD'));
			divs +=`
			<div class='item row'>
					<div class="col-md-2">
						<img data-src="${img}" alt="">
					</div>
					<div class="col-md-10">
						<div class="date ">作者：${author} ,${add_time} ,分类：<a href="/cate.html?cat_id=${cat_id}">${cate_name}</a></div>
						<a href='/detail.html?id=${id}'>
						<div class="title">${title}</div></a>
					</div>
					<hr>
			</div>
			`
		})
		imgs = document.querySelectorAll('img');
		return divs;
	}

	async function initData(){
		NProgress.set(0.4)
		let pro1 = loadCateArticle(page,pagesize,cat_id);
		let pro2 = loadCate();
		let data = await Promise.all([pro1,pro2]);
		NProgress.done();
	
		let [articles,cates] = data;
		// console.log(data)
		localStorage.setItem('cates',JSON.stringify(cates));
		let lis = renderCate(cates);
		$('#cates').html(lis);
		let divs = renderCateArticle(articles);
		$('#cateArticles').html(divs)
		imgs = document.querySelectorAll('img');
		scrollHandle(imgs);
	}
	window.onscroll = function(event){
		console.log('img',imgs);
		scrollHandle(imgs)
	};
	function scrollHandle(imgs) {
        // 获取网页卷上去的高度
        let pageScrollTop = document.documentElement.scrollTop || document.body.scrollTop;
        // 获取可视视口的高度
        let viewportHeight = window.innerHeight || document.documentElement.clientHeight;
        
		console.log('pageScrollTop"',pageScrollTop)
		console.log('viewportHeight',viewportHeight)
		imgs.forEach(img => {
			
			// 获取当前元素距离视口顶部的距离
			let {top} = img.getBoundingClientRect();

            // 进入视口前提前100px加载。防止读到空白页面
            if (top > 0 && top <  viewportHeight) {
                // 说明当前图片已经进入到可视区，
                if (img.getAttribute('loader') !== 'done') {
                    let src = img.getAttribute('data-src')
                    img.src = src;
                    // 给当前img设置一个自定义属性，记录是否已经加载过
                    img.setAttribute('loader', "done")
                    console.log('请求')
                } else {
                    console.log('已经加载过了')
                }

            }

        });


    }
	initData();
</script>
</html>